﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Data.Common;
using System.Data.SqlClient;
using System.Windows;
using PersonaLibrary.Properties;
using PersonaLibrary.Search;
using PersonaLibrary.Tracer;

namespace PersonaLibrary
{
	/// <summary>
	/// Interaction logic for App.xaml
	/// </summary>
	public partial class App
	{
		private ViewModel.MainWindowViewModel.MainWindowViewModel _mainViewModel;
		private Filter _filter;
		private const int FiltersInCashe = 5;
		private readonly ObservableCollection<Filter> _filters = new ObservableCollection<Filter>();
		private RelayCommand _goToFilterCommand;
		
		private void Application_Startup(object sender, StartupEventArgs e)
		{
			_filters.CollectionChanged += FiltersCollectionChanged;

			using (_mainViewModel = new ViewModel.MainWindowViewModel.MainWindowViewModel())
			{
				_mainViewModel.View.Closed += View_Closed;
				if (ServerAvailable)
				{
					UpdateBase();
				}

				_mainViewModel.View.ShowDialog();
			}
		}

		private static void UpdateBase()
		{
			using (DbConnection connection = new SqlConnection(Settings.Default.PersonalizationConnectionString))
			{
				connection.Open();

				string commandText =
					"IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Employee' AND COLUMN_NAME = 'Email')" +
					"BEGIN ALTER TABLE Employee ADD Email nvarchar(MAX) END";

				using (DbCommand command = new SqlCommand(commandText))
				{
					command.Connection = connection;
					command.ExecuteNonQuery();
				}
			}

		}

		void FiltersCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				if (_filters.Count > FiltersInCashe)
				{
					Action action = RemoveCollectionItem;
					Dispatcher.BeginInvoke(action, null);
				}
			}
		}

		void RemoveCollectionItem()
		{
			_filters.RemoveAt(0);
		}

		void View_Closed(object sender, EventArgs e)
		{
			Shutdown();
		}

		public ViewModel.MainWindowViewModel.MainWindowViewModel MainViewModel
		{
			get
			{
				return _mainViewModel;
			}
		}

		internal bool ServerAvailable { set; get; }

		internal event Action FilterChanged = delegate { };

		internal Filter Filter
		{
			get
			{
				return _filter;
			}
			set
			{
				if (_filter != null)
					_filter.PropertyChanged -= FilterPropertyChanged;
				_filter = value;
				if (_filter != null)
					_filter.PropertyChanged += FilterPropertyChanged;
				FilterChanged();
			}
		}

		internal ILogFacade Logger
		{
			get { return LoggerBuilder.GetLogger(); }
		}

		internal void GoToLoadView()
		{
			MessageBox.Show(Windows[Windows.Count - 1], "Load");
		}

		internal void GoToNormal()
		{
			
		}

		void FilterPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			FilterChanged();
		}

		private void Application_Exit(object sender, ExitEventArgs e)
		{
		}

		private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			Logger.Fault(e.Exception);
		}

		internal RelayCommand GoToFilterCommand
		{
			get
			{
				if(_goToFilterCommand == null)
					_goToFilterCommand = new RelayCommand(x => Filter = (Filter)x, x => x is Filter);
				return _goToFilterCommand;
			}
		}
	}
}
